/**
 * 封装的请求模块
 */
import axios from "axios";
import store from "../store";
import { Toast } from 'vant';
import router from '@/router'
import { getItem } from "@/utils/storage";
import user from "../store/module/user";
const  request = axios.create({
    baseURL: 'https://toutiao.itheima.net',
    timeout: 5000
})

// 请求拦截

request.interceptors.request.use(config => {
    const userToken = store.state.user.tokenInfo || getItem('user-token')
    config.headers.Authorization = `Bearer ${userToken ? userToken.token : ''}`
    return config
},error => {
    return Promise.reject(error)
})

// 响应拦截

request.interceptors.response.use( response =>{
    return response
}, error =>{
    if(error){
        let {status, data}  = error.response
        switch (status) {
            case 401:
                const user = store.state.user.tokenInfo || getItem('user-token')
                if (!user || !user.refresh_token) {
                    Toast.fail('登录信息失效，请重新登录！')
                    router.push({name:'Login'})
                    return
                }
                // 如果有refresh_token，则请求获取新的 token
                axios({
                    method: 'PUT',
                    url:'https://toutiao.itheima.net/v1_0/authorizations',
                    headers:{
                        Authorization: `Bearer ${user.refresh_token}`
                    }
                }).then( res => {
                    // 如果获取成功，则把新的 token 更新到容器中
                    store.commit('user/saveToken',res.data.data)
                    return request(error.config)
                },error=>{
                    // Toast.fail('登录信息失效，请重新登录！')
                    // router.push({name:'Login'})
                })
                break
            case 400:
                Toast.fail(data.message)
                return Promise.reject(data.message)
            case 429:
                Toast.fail(data.message)
        }
    }else{
        Toast.fail('网络异常，请稍后再试！')
    }
    console.log(error)
})

export default request
